package service

import (
	sqlc "bgs/db/sqlc"
	"bgs/grpc/gen/proxy2/bilinadmin"
	"bgs/util"
	"context"
	"fmt"
)

// EnsureUserAsBrandEmployee 确保用户成为品牌员工
func (s *UserServiceImp) EnsureUserAsBrandEmployee(ctx context.Context, q *sqlc.Queries, userID int64, brandID int64) (empID int64, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	user, err := q.GetUser(ctx, userID)
	if err != nil {
		return
	}
	if !user.Mobile.Valid {
		err = fmt.Errorf("EnsureUserAsBrandEmployee user mobile is invalid")
		return
	}

	userAccountToken, err := s.FetchUserAccountTokenSafely(ctx, q, &user)
	if err != nil {
		return
	}
	slog.Infof("EnsureUserAsBrandEmployee 获取用户的accountToken ok")

	cBrand := s.cacher.FetchBrand(brandID)
	if cBrand == nil {
		err = fmt.Errorf("not found brand of brandID:%d", brandID)
		return
	}
	sgID := cBrand.SgID
	req := &bilinadmin.EmployeeCreateRequest{
		BrandId:      sgID,
		AccountToken: userAccountToken,
	}

	slog.Infof("EmployeeCreate req:%v", req)

	ctxWithTimout, cancel := s.proxy.NewContextWith(ctx)
	defer cancel()
	reply, err := s.proxy.EmployeeCl.EmployeeCreate(ctxWithTimout, req)
	if err != nil {
		return
	}

	empID = reply.EmpId

	slog.Infof("确保用户成为品牌员工 ok")
	return
}
